//
//  Proxy.m
//  DialectShare
//
//  Created by timmy zhong on 3/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "Proxy.h"
#import "Reachability.h"
#import "JSON.h"
#import "Const.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "User.h"

@implementation Proxy
@synthesize object = _object, delegate = _delegate;

- (void)dealloc
{
    self.object = nil;
    
    [super dealloc];
}

- (BOOL)connectToNetwork
{
    return YES;
    
    if ([Proxy isExistenceNetwork]) {
            
        return YES;
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"请检查网络连接" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
    
    return NO;
}

- (void)showMessage:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    [User logout];
    [[UIApplication sharedApplication].keyWindow.rootViewController dismissModalViewControllerAnimated:YES];
}


- (NSString *)fetchDataForUrlString:(NSString *)url
{
    url = [url stringByAppendingFormat:@"&auth=%@", [User current].auth];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request startSynchronous];
    NSString *data = [request responseString];
    if ([data isEqualToString:@""]) {
        NSLog(@"sae挂了");
    }
    NSRange range = [data rangeOfString:@"{"];
    if (range.location < data.length) {
        data = [data substringFromIndex:range.location];
    } 
    
    [request release];
    
    return data;
}

- (NSString *)postData:(NSDictionary *)data files:(NSDictionary *)files url:(NSString *)url
{
    url = [url stringByAppendingFormat:@"&auth=%@", [User current].auth];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
    NSArray *keys = [data allKeys];
    for (NSString *key in keys) {
        [request setPostValue:[data objectForKey:key] forKey:key];
    }
    
    keys = [files allKeys];
    for (NSString *key in keys) {
        [request setFile:[files objectForKey:keys] forKey:key];
    }
    [request startSynchronous];
    
    NSString *rtn = [request responseString];
    NSRange range = [rtn rangeOfString:@"{"];
    if (range.location < rtn.length) {
        rtn = [rtn substringFromIndex:range.location];
    } 

    return rtn;
}

- (NSDictionary *)parse:(NSString *)data
{
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSDictionary *result = [parser objectWithString:data];
    if ([[result objectForKey:@"st"] intValue] == ServerStatusError 
        || [[result objectForKey:@"st"] intValue] == ServerStatusNoLogin
        || [[result objectForKey:@"st"] intValue] == ServerStatusPermissions) {

        [self performSelectorOnMainThread:@selector(showMessage:) withObject:[result objectForKey:@"msg"] waitUntilDone:YES];
    } 
    [parser release];
    return  result;
}


    
+ (BOOL)isExistenceNetwork
{
    BOOL isExistenceNetwork;
    Reachability *reachability = [Reachability reachabilityWithHostName:@"http://www.apple.com"];  // 测试服务器状态
    
    switch([reachability currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = FALSE;
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = TRUE;
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = TRUE;
            break;
    }
    return  isExistenceNetwork;
}

@end
